$(document).ready(function() {
	initialize();

});

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
	directionsDisplay = new google.maps.DirectionsRenderer();
	var chicago = new google.maps.LatLng(41.669, 1.516);
	var myOptions = {
		zoom : 10,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		center : chicago
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	//usuariMaps();

	var inputOrigen = document.getElementById('origen');
	var inputDesti = document.getElementById('desti');
	var options = {
		bounds : chicago,
		types : ['geocode']
	};
	autocompleteOrigen = new google.maps.places.Autocomplete(inputOrigen, options);
	$('#desti').focus(function() {
		var optionsDesti = {
			bounds : new google.maps.LatLng(41.670, 1.516),
			types : ['geocode']
		};

		autocompleteDesti = new google.maps.places.Autocomplete(inputDesti, optionsDesti);
	});

}

function calcRecorregut(origen, desti) {
	var aux = new Array();
	var request = {
		origin : origen,
		destination : desti,
		//unitSystem: google.maps.DirectionsUnitSystem["METRIC"],

		travelMode : google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {

			aux[0] = new Array();
			aux[1] = new Array();
			for (var i in response.routes) {
				var mylegs = response.routes[i].legs;
				/*for(var j in mylegs) {

				 aux = mylegs[j].start_location;

				 aux1 = mylegs[j].end_location;
				 }*/
				aux[0][0] = mylegs[0].start_location.lat();
				aux[0][1] = mylegs[0].start_location.lng();
				aux[0][2] = mylegs[0].start_address;

				aux[1][0] = mylegs[0].end_location.lat();
				aux[1][1] = mylegs[0].end_location.lng();
				aux[1][2] = mylegs[0].end_address;

			}

			//alert(aux);
			enviarDades(aux);

		}
	});

}

function enviarDades(aux) {

	$.post("insertarRuta.php", {
		enviar : aux
	}, function(data) {
		
		$('#recorregut2').show('slow');
	});
	$('#enviarFrm2').click(function(event) {
		

		var $aux1 = aux[0][2];
		
		var $aux2 = aux[1][2];

		$('input#origen2').val($aux1);
		$('input#desti2').val($aux2);
		
		event.preventDefault();
		$.post("insertaRecPassatger.php", $('#recorregut2').serialize());
	});

	$('#enviarFrm3').click(function(event) {
		//alert('Valor de aux: ' + aux[0][2] + aux[1][2]);

		var $aux1 = aux[0][2];
		var $aux2 = aux[1][2];

		$('input#origen2').val($aux1);
		$('input#desti2').val($aux2);

		
		event.preventDefault();
		$.post("insertaRecConductor.php", $('#recorregut2').serialize());
	});

}

//mostra el punt d'oringen del usuaris

